package com.zu.commu.remote.threads;

import com.zu.commu.context.ServerContext;
import com.zu.commu.remote.session.Session;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

public class ReadThreadManager
{
  Logger log = Logger.getLogger(ReadThreadManager.class);
  private static List<ReadThread> freeThreads;
  private static List<ReadThread> busiThreads;
  private static int maxThreadNum;
  private static int currThreadNum;
  private static int threadNum = 0;

  private static Object synObj = new Object();
  private static ReadThreadManager obj;

  public static ReadThreadManager instance()
  {
    if (obj == null) {
      obj = new ReadThreadManager();
    }
    return obj;
  }

  private ReadThreadManager()
  {
    busiThreads = new ArrayList<ReadThread>();
    freeThreads = new ArrayList<ReadThread>();
    maxThreadNum = ServerContext.maxThreadNumRemote;
    currThreadNum = 0;

    for (int i = 0; i < ServerContext.minThreadNumRemote; i++) {
      ReadThread t = new ReadThread(threadNum++);
      t.start();
      freeThreads.add(t);
      currThreadNum += 1;
      log.debug("【初始化空闲线程】ReadThread："+t.getName()+"并加入空闲线程池中！");
    }
  }

  public void readSocketChannel(Session se)
  {
	synchronized (synObj) {
		while (freeThreads.size() == 0) {
			if (currThreadNum < maxThreadNum) {
				ReadThread t = new ReadThread(threadNum++);
				log.debug("####已经没有空闲线程###开始【建立一个新的工作线程】ReadThread："
						+ t.getName());
				t.start();
				freeThreads.add(t);
				currThreadNum += 1;
			} else {
				do {
					try {
						log.debug("#####当前线程池已经达到服务设固定值：" + maxThreadNum
								+ ",主线程开始wait,等待有空闲线程出现在进行。。");
						synObj.wait();
					} catch (Exception e) {

						log.error("等待返回读socket的线程时发生等待异常!", e);
					}
				} while (freeThreads.size() == 0);
			}
		}
		ReadThread t = (ReadThread) freeThreads.get(0);
		freeThreads.remove(0);
		busiThreads.add(t);
		log.debug("【取一个空闲线程】ReadThread：" + t.getName());
		t.setReadSession(se);
	}
}
  /**
   * 加入一个空闲线程
   * @param threadNum 线程编号
   * @param t ReadThread
   */
  public void freeThread(int threadNum, ReadThread t)
  {
    synchronized (synObj) {
      busiThreads.remove(t);
      freeThreads.add(t);
      log.debug("【当前线程总数】："+currThreadNum);
      //log.debug("【加入一个空闲线程】："+t.getName()+":"+t.getState()+"-isCanRead:"+t.isCanRead()+"-isAlive:"+t.isAlive());
      log.debug("【当前空闲线程总数】："+freeThreads.size());
      //log.debug("【当前工作线程总数】："+busiThreads.size());
/*     if(busiThreads.size()>0){
    	  log.debug("*********当前工作线程*********");
    	  for (ReadThread element : busiThreads) {
    		  log.debug("*********"+element.getName()+":"+element.getState()+"-isCanRead:"+element.isCanRead()+"-isAlive:"+element.isAlive());
		  }
    	  log.debug("*********当前工作线程end******");    	  
      }*/
      synObj.notify();
    }
  }
}